/*
 * Created by 岱青海蓝信息系统(北京)有限公司 on 17-6-15 下午1:28
 * Copyright (c) 2017. All rights reserved.
 */

package com.example.dqhl.jdmetro.fragment;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.daimajia.slider.library.Animations.DescriptionAnimation;
import com.daimajia.slider.library.Indicators.PagerIndicator;
import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.SliderTypes.TextSliderView;
import com.example.dqhl.jdmetro.JDMetroApplication;
import com.example.dqhl.jdmetro.R;
import com.example.dqhl.jdmetro.activities.life.LifeLearnActivity;
import com.example.dqhl.jdmetro.activities.life.LifeServiceActivity;
import com.example.dqhl.jdmetro.base.BaseFragment;
import com.example.dqhl.jdmetro.bean.User;
import com.example.dqhl.jdmetro.bean.consulation.ConsulationBanner;
import com.example.dqhl.jdmetro.config.Config;
import com.example.dqhl.jdmetro.config.Constant;
import com.example.dqhl.jdmetro.utils.Dlog;
import com.example.dqhl.jdmetro.utils.JsonUtils;
import com.example.dqhl.jdmetro.utils.JumpItent;
import com.example.dqhl.jdmetro.utils.Toastutils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * description:生活汇
 * autour:guanluocang
 * date:17/6/15 13:32
 */
public class LifeFragment extends BaseFragment {

    private final static int REQUEST_CODE_PERMISSION_LOCATION = 300;
    //地图locationclient
    private AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    private AMapLocationClientOption mLocationOption = null;
    private String address = "";//定位地址
    private Double latitude;
    private Double longitude;
    private Context context;
    //轮播图
    @Bind(R.id.sliderLayout)
    SliderLayout sliderLayout;
    @Bind(R.id.custom_indicator)
    PagerIndicator custom_indicator;
    List<ConsulationBanner> bannerList = new ArrayList<>();

    @Bind(R.id.tv_learn)
    TextView tv_learn;
    @Bind(R.id.tv_play)
    TextView tv_play;
    @Bind(R.id.tv_move)
    TextView tv_move;
    @Bind(R.id.tv_shop)
    TextView tv_shop;
    @Bind(R.id.tv_address)
    TextView tv_address;//地址

    @Bind(R.id.iv_express)
    ImageView iv_express;//快递查询
    @Bind(R.id.iv_illegal)
    ImageView iv_illegal;//违法查询
    @Bind(R.id.iv_discount)
    ImageView iv_discount;//折扣
    @Bind(R.id.iv_calendar)
    ImageView iv_calendar;//日历

    @Override
    public View initView(LayoutInflater inflater) {
        rootView = inflater.inflate(R.layout.fragment_life, null);
        ButterKnife.bind(this, rootView);
        context = getActivity();
        registerBroadcastReceiver();
        initTitleBar(rootView, R.string.txt_life);
        setLeftBackVisibility(rootView, View.GONE);
        return rootView;
    }


    @Override
    public void initData() {
        getBannerData();
    }

    @Override
    public void initListener() {
        tv_learn.setOnClickListener(this);
        tv_play.setOnClickListener(this);
        tv_move.setOnClickListener(this);
        tv_shop.setOnClickListener(this);
        iv_express.setOnClickListener(this);
        iv_illegal.setOnClickListener(this);
        iv_discount.setOnClickListener(this);
        iv_calendar.setOnClickListener(this);
    }

    /**
     * 广播接收者
     */
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Constant.ACTION_LOGIN_SUCCESS)) {
                user = (User) intent.getExtras().get("user");
                Dlog.e(user.toString());
            } else if (action.equals(Constant.ACTION_LOGOUT_SUCCESS)) {
                user = null;
            }
        }
    };

    /**
     * 注册广播接收者
     */
    private void registerBroadcastReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_LOGIN_SUCCESS);
        intentFilter.addAction(Constant.ACTION_LOGOUT_SUCCESS);
        context.registerReceiver(receiver, intentFilter);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_learn:
                if (user == null) {
                    Toastutils.show("请先登录");
                } else if (latitude == null || "".equals(latitude)) {
                    checkLocationPermission();
                    Toastutils.show("正在定位...");
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putDouble("latitude", latitude);
                    bundle.putDouble("longitude", longitude);
                    bundle.putString("type", "1");
                    JumpItent.jump(getActivity(), LifeLearnActivity.class, bundle);
                }

                break;
            case R.id.tv_play:
                if (user == null) {
                    Toastutils.show("请先登录");
                } else if (latitude == null || "".equals(latitude)) {
                    checkLocationPermission();
                    Toastutils.show("正在定位...");
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putDouble("latitude", latitude);
                    bundle.putDouble("longitude", longitude);
                    bundle.putString("type", "2");
                    JumpItent.jump(getActivity(), LifeLearnActivity.class, bundle);
                }
                break;
            case R.id.tv_move:
                if (user == null) {
                    Toastutils.show("请先登录");
                } else if (latitude == null || "".equals(latitude)) {
                    checkLocationPermission();
                    Toastutils.show("正在定位...");
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putDouble("latitude", latitude);
                    bundle.putDouble("longitude", longitude);
                    bundle.putString("type", "3");
                    JumpItent.jump(getActivity(), LifeLearnActivity.class, bundle);
                }
                break;
            case R.id.tv_shop:
                if (user == null) {
                    Toastutils.show("请先登录");
                } else if (latitude == null || "".equals(latitude)) {
                    Toastutils.show("正在定位...");
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putDouble("latitude", latitude);
                    bundle.putDouble("longitude", longitude);
                    bundle.putString("type", "4");
                    JumpItent.jump(getActivity(), LifeLearnActivity.class, bundle);
                }
                break;
            //快递查询
            case R.id.iv_express:
                Bundle bundle_express = new Bundle();
                bundle_express.putString("service", "1");
                JumpItent.jump(getActivity(), LifeServiceActivity.class, bundle_express);
                break;
            //违章
            case R.id.iv_illegal:
                Bundle bundle_illegal = new Bundle();
                bundle_illegal.putString("service", "2");
                JumpItent.jump(getActivity(), LifeServiceActivity.class, bundle_illegal);
                break;
            //折扣
            case R.id.iv_discount:
                Bundle bundle_discount = new Bundle();
                bundle_discount.putString("service", "3");
                JumpItent.jump(getActivity(), LifeServiceActivity.class, bundle_discount);
                break;
            //日历
            case R.id.iv_calendar:
                Bundle bundle_calendar = new Bundle();
                bundle_calendar.putString("service", "4");
                JumpItent.jump(getActivity(), LifeServiceActivity.class, bundle_calendar);
                break;

        }
    }


    /**
     * 检查定位权限
     */
    private void checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    REQUEST_CODE_PERMISSION_LOCATION);
        } else {
            initLocation();
        }
    }

    /**
     * 定位
     */
    private void initLocation() {
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //获取联网超时时间
        mLocationOption.setHttpTimeOut(2000);
        //获取最近3s内精度最高的一次定位结果
        mLocationOption.setOnceLocationLatest(true);
        mLocationClient = JDMetroApplication.getInstance().mLocationClient;
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //设置定位回调监听
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        address = aMapLocation.getAddress();
                        latitude = aMapLocation.getLatitude();
                        longitude = aMapLocation.getLongitude();
                        Dlog.e("当前位置:" + address);
                        tv_address.setText(address);
                    } else {
                        address = "定位失败";
                        tv_address.setText(address);
                        Dlog.e("定位失败");
                        Dlog.e("location Error, ErrCode:" + aMapLocation.getErrorCode()
                                + ", errInfo:" + aMapLocation.getErrorInfo());
                    }
                }
            }
        });
        //启动定位
        mLocationClient.startLocation();
    }

    /**
     * 获取轮播图数据
     */
    private void getBannerData() {
        RequestParams params = new RequestParams(Config.consulation_banner);
        x.http().get(params, new Callback.CacheCallback<String>() {
            @Override
            public boolean onCache(String result) {
                return false;
            }

            @Override
            public void onSuccess(String result) {
                Dlog.e("banner数据" + result);
                int errCode = JsonUtils.getErrCode(result);
                String errMsg = JsonUtils.getErrMsg(result);
                String data = JsonUtils.getData(result);
                if (errCode == 200) {
                    bannerList = JSON.parseArray(data, ConsulationBanner.class);
                    for (int i = 0; i < bannerList.size(); i++) {
                        //新建三个展示View，并且添加到SliderLayout
                        TextSliderView tsv = new TextSliderView(getActivity());
                        tsv.image(Config.pic_base_url + bannerList.get(i).getPic());
                        final int finalI = i;
                        tsv.setOnSliderClickListener(new BaseSliderView.OnSliderClickListener() {
                            @Override
                            public void onSliderClick(BaseSliderView slider) {
                                Toast.makeText(getActivity(), bannerList.get(finalI).getTitle(), Toast.LENGTH_SHORT).show();
                            }
                        });
                        sliderLayout.addSlider(tsv);
                    }

                    //对SliderLayout进行一些自定义的配置
                    sliderLayout.setCustomAnimation(new DescriptionAnimation());
                    //设置滑动的动画
                    sliderLayout.setPresetTransformer(SliderLayout.Transformer.Tablet);
                    sliderLayout.setDuration(3000);
                    //      sliderLayout.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
                    sliderLayout.setCustomIndicator(custom_indicator);
                } else {
                    Toastutils.show(errMsg);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
        }
        if (receiver != null) {
            context.unregisterReceiver(receiver);
        }
    }
}
